/*
 * @Description: 
 * @Author: Chenx
 * @Date: 2023-03-22 15:00:18
 * @LastEditors: Chenx
 * @LastEditTime: 2023-03-24 14:49:19
 */
import axios, { type AxiosRequestConfig } from 'axios'
// import { Toast } from 'vant'
import { userStore } from "@/store/modules/user"
import { getLocale } from '@/locals'
const { VITE_ENV, VITE_BASE_API, VITE_BASE_URL } = import.meta.env
const IS_PROD = ['production', 'prod'].includes(VITE_ENV)
const baseURL = IS_PROD ? VITE_BASE_URL + VITE_BASE_API : VITE_BASE_API

const https = () => {
  const user = userStore()
  const config: AxiosRequestConfig = {
    baseURL,
    timeout: 20000,
    headers: {
      language: 'tc',
      Authorization: user.getToken
    }
  }
  /* 初始化axioas */
  const service = axios.create(config)
  /* 请求拦截器 */
  service.interceptors.request.use(
    (config) => {
      // do something
      if (config.url!.indexOf('oauth') > -1) {
        config.baseURL = IS_PROD ? VITE_BASE_URL + '/auth' : '/auth'
      } else {
        config.baseURL = baseURL
      }

      return config
    },
    (error) => {
      // 拦截接口超时
      const isTimeOut = error.code == 'ECONNABORTED' && error.message.indexOf('timeout') !== -1
      // if (isTimeOut) {
      //   Toast && Toast.clear()
      //   Toast && Toast.fail('网络繁忙，请稍后重试')
      // }
      // // 处理响应失败
      return Promise.reject(error)
    }
  )

  /* 响应拦截器 */
  service.interceptors.response.use(
    (response) => {
      // do something
      console.log('http请求返回值：', response.data)
      if (response.data.code == '101101') { // 修复
        // jsBridge.toLogin()
      }
      return Promise.resolve(response.data)
    },
    (error) => {
      // 拦截接口超时
      const isTimeOut = error.code == 'ECONNABORTED' && error.message.indexOf('timeout') !== -1
      // if (isTimeOut) {
      //   Toast && Toast.clear()
      //   Toast && Toast.fail('网络繁忙，请稍后重试')
      // }
      // 处理响应失败
      return Promise.reject(error)
    }
  )

  return service
}

export enum Method {
  GET = 'GET',
  POST = 'POST',
  PUT = 'PUT',
  PATCH = 'PATCH',
  DELETE = 'DELETE'
}

export enum ContentType {
  form = 'application/x-www-form-urlencoded',
  json = 'application/json; charset=utf-8',
  multipart = 'multipart/form-data'
}
/**
 * 网络请求参数
 */
export interface RequestParams {
  [key: string]: any
}

export default https
